﻿package com.ufenlei.LTS{
	import flash.display.Sprite;
	import flash.display.MovieClip;
	import flash.text.TextField;
	import flash.net.URLLoader;
	import flash.net.URLRequest;
	import flash.events.Event;
	import flash.events.MouseEvent;
	import flash.events.ProgressEvent;
	import flash.display.SimpleButton;
	import flash.display.StageScaleMode;
	import flash.display.Stage;
	import flash.utils.Timer;
	import flash.events.TimerEvent;
	import flash.events.IOErrorEvent;

	import com.ufenlei.tool.RoundRectangle;

	public class ListeningTestSystem extends Sprite{
		private var _id:uint;
		private var _title:String;
		private var _tgList:Array;
		private var _url:String;
		private var _window:Window;
		private var _libWindow:Window;
		private var _smallWindow:Window;
		private var _smallText:TextBlock;
		private var _player:TestingPlayer;
		private var _topBar:RoundRectangle = new RoundRectangle(800,20,0.6,0xffffff,0,0x000000,0,0,0,0,20);
		private var _bottomBar:RoundRectangle =new RoundRectangle(800,20,0.6,0xffffff,0,0x000000,0,20,0,0,0);
		private var _mask:RoundRectangle = new RoundRectangle(800,600,0.8,0x000000,0);
		private var _loadBar:LoadingBar;
		private var swidth:int = 800;
		private var sheight:int = 600;
		private var currentTG:TestingGroup;
		private var _TGRadio:TestingGroupList = new TestingGroupList();
		private var _xmlLoader:URLLoader;
		private var _totalNum:int = 0;
		private var _task:int = 0;
		private const TASK_LOADTEST:int = 1;
		private var _loadedNum:int = 0;
		private var _screenAdjustinited:Boolean = false;
		private var _backgroundimage:ImageLoader;
		private var _layoutList:Array;
		private var _resultBlock:TestingResult;
		private var _checkbtn:CheckButton;
		private var _mainmanubtn:MainMenuButton;
		private var layout:SimpleLayout;
		
		public function ListeningTestSystem(testURL:String = null){
			_url = testURL;
			_tgList = new Array();
			_window = new Window(this, 760, 400, "Main",false,true);
			_player = new TestingPlayer();
			layout = new SimpleLayout();
			this._loadBar = new LoadingBar();			
			_player.x = 10;
			_player.y = 500;
			_backgroundimage = new ImageLoader(1280,800,false);
			_backgroundimage.load("http://ufenlei.com/lts/image/TwistedLight_1.jpg");
			_backgroundimage.addEventListener(Event.COMPLETE, onBackgroundReady);
			addChild(_backgroundimage);
			layout.add(_backgroundimage, '50%', '50%');
			addChild(_topBar);
			addChild(_bottomBar);
			_smallWindow = new Window(this,400,200,"提示",false,true,false,1.0);
			_libWindow = new Window(this, 710,420,"浏览试题库",false,true);
			_smallText = new TextBlock(400,180),
			_smallWindow.addContent(_smallText);
			//_mainmanubtn = new MainMenuButton();
			//addChild(_mainmanubtn);
			this.addChild(sitecert as TextField);
			trace(sitecert.x,sitecert.y,sitecert.width,sitecert.height);
			layout.add(sitecert,null,'50%',0);
			//layout.add(_mainmanubtn, null, null,20,20);
			_checkbtn = new  CheckButton();
			//_mainmanubtn.addEventListener(Input.CLICK, onCheckBtnClick);
			this.addEventListener(Event.ADDED_TO_STAGE, onAddToStage);
			var t:Timer = new Timer(10);
			t.addEventListener(TimerEvent.TIMER, onTimer);
			t.start();
			loadList();
		}
		private function onTimer(evt:TimerEvent) : void {
			trace("onTimer");
			if((stage as Stage) == null){
				return;
			}else{
				trace("StageExsit",_screenAdjustinited);
				//if(!_screenAdjustinited){
					this.removeEventListener(Event.ADDED_TO_STAGE, onAddToStage);
					initScreenAdjust();
				//}else{
					(evt.target as Timer).stop();
				    (evt.target as Timer).removeEventListener(TimerEvent.TIMER, onTimer);	
				//}	
				
			}
		}
		
		private function initScreenAdjust():void{
			//showMessage("stage",stage is Stage);
			_screenAdjustinited = true;
//Set Scale Mode,设定缩放模式为无缩放
			stage.scaleMode=StageScaleMode.NO_SCALE;
//Set Screen adjust event,设置屏幕缩放
			stage.addEventListener(Event.RESIZE,screenAdjust);
//在程序初始时就调用一下界面调整
			screenAdjust(null);
		}
		private function onBackgroundReady(evt:Event):void{
			(evt.target as ImageLoader).addEventListener(Event.COMPLETE, onBackgroundReady);
			screenAdjust(null);
		}
		private function showMessage(... args):void{
			showMask();
			if(args[0] is Sprite){
				_smallWindow.clearAllContent();
				_smallWindow.addContent(args[0]);
				(args[0] as Sprite).x = (args[1])?args[1]:0;
				(args[0] as Sprite).y = (args[2])?args[2]:0;
			}else{
				_smallWindow.addContent(_smallText);
				_smallText.text = args.join("");
			}
			this._smallWindow.x = (swidth - _smallWindow.width) / 2;
			this._smallWindow.y = (sheight - _smallWindow.height) / 2;
			this._smallWindow.open();
			
			this._smallWindow.addEventListener(Event.CLOSE, onSmallWindowClose);
		}
		private function showMask():void{
			this.addChild(_mask);
		}
		private function hideMask():void{
			this.removeChild(_mask);
		}
		private function showLoadBar():void{
			addChild(_loadBar);
			_loadBar.init();
		}
		private function hideLoadBar():void{
			removeChild(_loadBar);
		}
		private function screenAdjust(evt:Event):void{
			var offX:int=Math.floor((800 -stage.stageWidth)/2);
			var offY:int=Math.floor((600-stage.stageHeight)/2);
			this.x=offX;
			this.y=offY;
			swidth = stage.stageWidth;
			sheight = stage.stageHeight;
			layout.update(swidth, sheight);
			layout.freshView();
			this._window.x = Math.max(stage.stageWidth - 780, 0 )/2;
			this._window.y = 50;
			if(sheight >= this._window.winHeight + 50){
				this._window.y = 50;
			}else{
				this._window.y = Math.max(sheight - this._window.winHeight,0);
			}
			this._topBar.w = stage.stageWidth;
			this._bottomBar.w = stage.stageWidth;
			this._bottomBar.y = stage.stageHeight - this._bottomBar.height;
			this._player.y = this._bottomBar.y - this._player.height;
			this._loadBar.x = (swidth - this._loadBar.width)/2;
			this._loadBar.y = (sheight - this._loadBar.height)/2;
			this._libWindow.x =(swidth - _libWindow.width)/2;
			if(sheight >= this._libWindow.winHeight + 50){
				this._libWindow.y = 50;
			}else{
				this._libWindow.y = Math.max(sheight - this._libWindow.winHeight, 0);
			}
			_mask.w = swidth;
			_mask.h = sheight;
		}
		public function check():void{
			var gNum:int = 0;
			var iNum:int = 0;
			var answerdNum:int = 0;
			var rightNum:int = 0;
			var score:int = 0;
			for each (var tg:TestingGroup in _tgList){
				gNum++;			
				tg.showKey();
				for each(var ti:TestingItem in tg.list){
					iNum++;
					if(ti.status == TestingItem.STATUS_FINISHED){
						answerdNum++;
						if (ti.check()){
							rightNum++;
							score += ti.score;
						}
					}
				}
			}
			if(!_resultBlock) {
				_resultBlock = new TestingResult();
			}
			this._resultBlock.setScore(score);
			this._resultBlock.setRight(rightNum);
			this._resultBlock.setTotal(iNum);
			this.showMessage(_resultBlock,60,20);
		}
		private function onAddToStage(evt:Event):void{
			initScreenAdjust();
		}
		private function onSmallWindowClose(evt:Event):void{
			this.hideMask();
		}
		//TestingGroup准备好之后调用 init
		private function initLTS():void{
			_TGRadio = null;
			_TGRadio = new TestingGroupList();
			_tgList.forEach(function(item:TestingGroup,idx:uint,arr:Array):void{
				_TGRadio.add(item,idx);
			});
			_window.clearAllContent();
			this.currentTG = null;
			_window.addContent(_TGRadio);
			_checkbtn = new CheckButton();
			_checkbtn.addEventListener(Input.CLICK, onCheckBtnClick);
			_window.addContent(_checkbtn);
			_checkbtn.x = 630;
			_checkbtn.y = 250;
			_TGRadio.x = 600;
			_TGRadio.y = 5;
			_TGRadio.addEventListener(Input.CHANGE,onTGRChange);
			_TGRadio.addEventListener(Input.CLICK,onTGClick);
			_window.open();
			_window.addEventListener(Event.CLOSE, onWindowClose);
			_TGRadio.turnOn(0);
		}
		private function onCheckBtnClick(evt:Event):void{
			this.check();
		}
		private function onWindowClose(evt:Event):void{
			trace("_window Close",evt.target);
			if(evt.target == _window){
				_libWindow.open();
				_player.stopPlay();
				this.removeChild(_player);
			}
			if(evt.target == _libWindow){
				if(this._task == TASK_LOADTEST){
					this.load(_url);
					this._task = 0;
				}
			}
		}
		private function onTGClick(evt:Event):void{
			if(!_window.isopen){
				_window.open();
			}
		}
		private function onTGRChange(evt:Event):void{
			playTestGroup((evt.target as TestingGroupList).idx);
		}
		private function playTestGroup(i:int = 0):void{
			if(this.currentTG) {
				_window.clearContent(currentTG);
			}
			this.currentTG = _tgList[i];
			this.addChild(_player);
			_player.load(_tgList[i].soundURL);
			_window.addContent(_tgList[i]);
			_window.setTitle(_tgList[i].title);
		}
		private function loadList():void{
			var lb:TestingLib = new TestingLib(700,380,500);
			lb.addEventListener(Event.OPEN, onLoaderOpen);
			lb.addEventListener(Event.COMPLETE, onLibComplete);
			lb.addEventListener(Input.CLICK, onLibClick);
			lb.load("http://ufenlei.com/xml/lib");
			lb.x = 5;
			lb.y = 5;
			_libWindow.addContent(lb);
		}
		private function onLibClick(evt:Event):void{
			if(evt.target is TestingLibItem){
				var litem:TestingLibItem = evt.target as TestingLibItem;
				_url = litem.url;
				_libWindow.close();
				_task = TASK_LOADTEST;
				_libWindow.addEventListener(Event.CLOSE, onWindowClose);
			}
		}
		private function onLoaderOpen(evt:Event):void{			
			if(evt.target is TestingLib){
				this.showMask();
				var lb:TestingLib = evt.target as TestingLib;
				lb.addEventListener(ProgressEvent.PROGRESS,onLoaderProgress);
				showLoadBar();
			}
			if(evt.target == _xmlLoader){
				this.showMask();
				showLoadBar();
				_xmlLoader.addEventListener(ProgressEvent.PROGRESS, onLoaderProgress);
			}
		}
		private function onLibComplete(evt:Event):void{
			if(evt.target is TestingLib){
				var lb:TestingLib = evt.target as TestingLib;
				lb.removeEventListener(ProgressEvent.PROGRESS,onLoaderProgress);
				this.hideLoadBar();
				this.hideMask();
				_libWindow.open();
				_libWindow.warningString = "你确定要关闭试题库吗？";
			}			
		}
		private function onLoaderProgress(evt:ProgressEvent):void{
			if(evt.target == _xmlLoader){
				_loadBar.setProgress(evt.bytesLoaded, evt.bytesTotal/0.1);
			}else{
				_loadBar.setProgress(evt.bytesLoaded, evt.bytesTotal);
			}			
		}
		private function load(testURL:String = null):void{
			if(testURL){
				_url = testURL;
			}
			var myXMLURL:URLRequest = new URLRequest(_url);
			_xmlLoader = new URLLoader();
			_xmlLoader.addEventListener("complete", xmlLoaded);
			_xmlLoader.addEventListener(Event.OPEN, onLoaderOpen);
			_xmlLoader.addEventListener(IOErrorEvent.IO_ERROR,onIOError);
			_xmlLoader.load(myXMLURL);
		}
		private function xmlLoaded(event:Event):void{
			var myXML:XML = new XML((event.target as URLLoader).data);
			trace("XML(",_url,") loaded.");
			trace(myXML);
			this.addEventListener(Event.COMPLETE, handleComplete);
			this._title = 	myXML.elements("testingTitle");
			this._id 	= 	parseInt(myXML.elements("testingId"));
			_tgList = new Array();
			this._totalNum = myXML.elements("*").elements("testingItem").length();
			this._loadedNum = 0;
			for each(var tg in myXML.testingGroup){ 
				var thetg:TestingGroup = new TestingGroup(tg.index,
														tg.title,
														tg.@soundtrack ,														
														590,
														350,
														tg.@type);
				thetg.addEventListener(Event.COMPLETE, handleComplete);
				thetg.x = 5; 
				thetg.y = 5;
				for each(var ti:XML in tg.testingItem){
					thetg.add( new TestingItem( ti.@index, 
												getXMLOption(ti),
												ti.optionGroup.@type, 
												ti.@key , 
												ti.@question,
												ti.@score));
				}
				this._tgList.push(thetg);
			}			
		}
		private function onIOError(evt:IOErrorEvent):void{
			if(evt.target == _xmlLoader){
				this.load();
			}
		}
		private function handleComplete(evt:Event):void{
			if(evt.target is TestingItemView){
				_loadedNum++;
				trace(_loadedNum,'/',this._totalNum);
				this._loadBar.setProgress(_loadedNum*90 + _totalNum*10, _totalNum*100);
				if(_loadedNum == _totalNum){
					this.hideMask();
					this.hideLoadBar();
					initLTS();
				}
			}			
		}
		private function getXMLOption(ti:XML):Array{
			var ol:Array = new Array();
			for each(var option in ti.optionGroup.option){
				ol.push({key: option.@index,desc:option.@desc});
			}
			return ol;
		}
	}
}